import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

class ResponseHandleThread extends Thread {
    private DatagramPacket packet;
    private DatagramSocket socket;

    public ResponseHandleThread(DatagramPacket packet, DatagramSocket socket) {
        this.packet = packet;
        this.socket = socket;
    }

    @Override
    public synchronized void run() {
        byte[] payload = packet.getData();
        try {
            // while(!flag){}
            // flag = false;
            HashMap<String, String> rMap = Server.bytes2Map(payload);
            String tId = rMap.get("ID");
            for (HashMap<String, String> map : Server.mapList) {
                if (map.get("ID").equals(tId)) {
                    String host = map.get("CLIADDR").replaceAll("/", "").split(":")[0];
                    Integer port = Integer.parseInt(map.get("CLIADDR").replaceAll("/", "").split(":")[1]);
                    SocketAddress clientAddr = new InetSocketAddress(host, port);
                    DatagramPacket rPacket = new DatagramPacket(payload, payload.length, clientAddr);
                    socket.send(rPacket);
                    if(Server.dbgLvFlag>=1)
                        System.out.println("Send to " + host + ":" + port + " -- " + rMap);
                    Server.mapList.remove(map);
                }
            }
            // flag = true;
        } catch (UnsupportedEncodingException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}